package cn.mygweb.common.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.mygweb.common.pojo.JsonResult;

/** 
* <p>Title: ExceptionHandler.java</p>
* <p>Description: 全局异常捕获处理类，捕获所有Controller中抛出的异常</p>  
* @author gxb 
* @date 2019年5月19日 
* <p>Copyright: Copyright (c) 2019</p>
* <p>Company: www.mygweb.cn</p> 
*/
// 加强Controller,也就是@ControllerAdvice注解，有这个注解的类中的方法
// 的某些注解会应用到所有的Controller里，其中就包括@ExceptionHandler注解。
@ControllerAdvice	
public class GlobalExceptionHandler {

	/**
	 * 返回错误的页面
	 */
	public static final String ERROR_VIEW = "error";
	
	
	/**
	 * <p>Title: SysExceptionHandler</p>
	 * <p>Description: 全局SysException异常处理</p>
	 * @param e
	 * @return
	 */
	@ExceptionHandler(SysException.class)
	@ResponseBody
	private Object SysExceptionHandler(SysException e) {
		e.printStackTrace();
		ModelAndView mav = new ModelAndView();
		if(e.getStatus() == 404) {
			mav.addObject("msg",e.getMessage());
			mav.setViewName("404error");
			return mav;
		}else if(e.getStatus() == 500) {
			mav.addObject("msg",e.getMessage());
			mav.setViewName("500error");
			return mav;
		}
		return JsonResult.build(e.getStatus(), e.getMessage(), null);
	}
	
	/**
	 * <p>Title: errorHandler</p>
	 * <p>Description: 全局Exception异常处理</p>
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	private Object errorHandler(HttpServletRequest request,HttpServletResponse response, Exception e) {
		
		e.printStackTrace();
		
		if(isAjax(request)) {
			return JsonResult.errorException(e.getMessage());
		}else {
			ModelAndView mav = new ModelAndView();
			mav.addObject("exception",e);
			mav.addObject("url", request.getRequestURL());
			mav.setViewName(ERROR_VIEW);
			return mav;
		}
	}
	
	
	/**
	 * <p>Title: isAjax</p>
	 * <p>Description: 判断是否是ajax请求</p>
	 * @param request
	 * @return
	 */
	public static boolean isAjax(HttpServletRequest request) {
		return request.getHeader("X-Requested-with") != null
				&& "XMLHttpRequest".equals(request.getHeader("X-Requested-with").toString());
	}
	
}
